<?php
namespace app\api\controller;
use think\Db;
use think\Log;

class Pool extends Base
{
    private $todayTime;
    private $todayDate;
    public function __construct()
    {
        extract(input());
        $this->todayTime = date('Y-m-d H:i:s');
        $this->todayDate = date('Y-m-d');
//        if(!isset($mini)){
//            $sta = $this->checkAll ($user_id,$time,$value,$reqKey);
//            if(!$sta){
//                return json(['status'=>301,'msg'=>'Token失效！请重新登录！']);
//            }
//        }
//        parent::_initialize ();
    }
    public function getConfigInfo($type)
    {
        $res = Db::table('up_jifen_conf')->where('conf_id',$type)->find();
        return $res;

    }
    public function getUserInfo($user_id,$field='',$type=1)
    {
        if($field){
            if($type == 1){
                $res = Db::table('up_u_user')->where('user_id',$user_id)->value($field);
            }else{
                $res = Db::table('up_u_user')->where('user_id',$user_id)->field($field)->find();
            }
        }else{
            $res = Db::table('up_u_user')->where('user_id',$user_id)->find();
        }
        return $res;

    }
    public function handleGoodsInfo($data,$user_id='',$store_uid='')
    {
        foreach ($data as $k => $v){
            //图片
            if($v['p_banner']){
                $data[$k]['p_banner'] = explode(',',$v['p_banner'])[0];
            }else{
                $data[$k]['p_banner'] = [];
            }
            //价格
            if($v['p_model'] == 2){
                $price = Db::table('up_product_model')
                    ->where('m_product_id',$v['p_id'])
                    ->order('m_price asc')
                    ->value('m_price');
                $data[$k]['p_now_price'] = $price;
            }
            //是否已加入
            if($user_id){
                $have = Db::table('up_m_goods')
                    ->where('good_user_id',$user_id)
                    ->where('good_p_id',$v['p_id'])
                    ->field('good_id')
                    ->find();
                $data[$k]['have'] = 1;
                if($have){
                    $data[$k]['have'] = 2;
                }
            }
            //----------团团赚的情况下的信息-----
            if($v['p_m_team_status'] == 1){
                if(!$store_uid){
                    $store_uid = 0;
                }
                $haveUsers = Db::name('m_order')
                    ->where('mo_status', 1)
                    ->where('mo_pay_status', 2)
                    ->where('mo_store_uid', $store_uid)
                    ->where('mo_p_id', $v['p_id'])
                    ->column('mo_user_id');
                $data[$k]['users'] = []; //参与者头像
                if($haveUsers){
                    $data[$k]['users'] = Db::name('u_user')->where('user_id', 'in',$haveUsers)->column('user_image');
                }
                $data[$k]['need'] = $v['p_m_team_nums'] - count($haveUsers); //还差几人成团
                $data[$k]['isjoin'] = 1; //我没有参与
                if(in_array($user_id,$haveUsers)){
                    $data[$k]['isjoin'] = 2; //我有参与
                }
                if($store_uid > 0){
                    $last = Db::name('m_goods')
                        ->where('good_user_id', $store_uid)
                        ->where('good_p_id', $v['p_id'])
                        ->field('good_team_status,good_team_end_time')
                        ->find();
                    $data[$k]['endStatus'] = $last['good_team_status']; //是否已开始（是否有人参加）
                    $data[$k]['endTime'] = $last['good_team_end_time']; //结束时间
                }else{
                    $data[$k]['endStatus'] = $v['p_m_team_can_status']; //是否已开始（是否有人参加）
                    $data[$k]['endTime'] = $v['p_m_team_can_endtime']; //结束时间
                }
            }
        }
        return $data;

    }
    public function locationGet (){
        extract(input());
        if(isset($id) && $id){
            $res = Db::table('up_area')
                ->where('pid',$id)
                ->select();
        }else{
            $res = Db::table('up_area')
                ->where('pid',1)
                ->select();
        }
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function userInfo(){
        extract(input());
        $zong = $this->getUserInfo($user_id);
        $money = [];
        $money['all_money'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->sum('record_money');
        $money['will_money'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->whereTime('record_add_time','today')
            ->sum('record_money');
        $money['all_jifen'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->sum('record_jifen');
        $money['will_jifen'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->whereTime('record_add_time','today')
            ->sum('record_jifen');
        return json(['status'=>200,'msg'=>$zong,'money'=>$money]);
    }
    /**
     * 开通小店
     * @return \think\response\Json
     */
    public function openStore(){
        extract(input());
        $user = $this->getUserInfo($user_id,'user_level,user_m_open,user_invite_code',2);
        if($user['user_level'] > 1 && $user['user_m_open'] == 1){
            if(!$user['user_invite_code']){
                return json(['status'=>100,'msg'=>'邀请码错误，无法开启小店！']);
            }
            $url =  'https://csdl.jintianjifen.cn';
            $ercode = Qrcode($url . "/api/Pool/saoma?type=fenyong&uid={$user_id}&incode={$user['user_invite_code']}");
            $res = Db::table('up_u_user')->where('user_id',$user_id)->update([
                'user_m_open' => 2,
                'user_m_ercode' => $url . $ercode,
                'user_m_open_time' => $this->todayTime
            ]);
            if($res){
                return json(['status'=>200,'msg'=>'开通成功']);
            }else{
                return json(['status'=>100,'msg'=>'开通失败，请刷新重试！']);
            }
        }else{
            return json(['status'=>100,'msg'=>'只有未开过小店的合伙人才可以开店！']);
        }
    }
    /**
     * 编辑小店信息
     * @return \think\response\Json
     */
    public function editStore(){
        extract(input());
        $update = [
            'user_edit_time' => $this->todayTime
        ];
        if(isset($user_m_name) && $user_m_name){
            $update['user_m_name'] = $user_m_name;
        }
        if(isset($user_m_logo) && $user_m_logo){
            $update['user_m_logo'] = $user_m_logo;
        }
        if(isset($user_m_desc) && $user_m_desc){
            $update['user_m_desc'] = $user_m_desc;
        }
        $res = Db::table('up_u_user')->where('user_id',$user_id)->update($update);
        if($res){
            $res = Db::table('up_u_user')->where('user_id',$user_id)->find();
            return json(['status'=>200,'msg'=>$res]);
        }else{
            return json(['status'=>100,'msg'=>'修改失败，请刷新重试！']);
        }
    }

    /**
     * 产品池的商品库或者店主自己看自己的店详情或者店主添加
     * @return \think\response\Json
     */
    public function chooseGoods(){
        extract(input());
        $map = [
            'p_status' => 4,
            'p_type' => 1,
            'p_m_pool' => 3,
        ];
        $map2 = [];
        $order = 'p_sort desc';
        $store_uid = '';
        if(isset($uid) && $uid){ //我自己看
            $pids = Db::table('up_m_goods')
                ->where('good_user_id',$uid)
                ->column('good_p_id');
            $map['p_id'] = ['in',$pids];
            $store_uid = $uid;
        }
        $user = $this->getUserInfo($user_id,'user_city,user_area',2);
        $flag = true;
        if(isset($post) && $post == 1){ //全国包邮
            $map['p_deliver_cate'] = 1;
            $flag = false;
        }
        if(isset($my_city) && $my_city){ //本地
            $map['shop_qu_id'] = $my_city;
            if(isset($area) && $area){
                $map['shop_qu_id'] = $area;
            }
            $flag = false;
        }
        if(isset($city) && $city){ //城市
            $map['shop_qu_id'] = $city;
            $flag = false;
        }
        if(isset($keyword) && $keyword){ //关键字
            $map['p_name'] = ['like',"%$keyword%"];
        }
        if(isset($team_status) && $team_status == 1){ //允许开团
            $flag = false;
            $map['p_m_team_status'] = 1;
            if(isset($area) && $area){
                $map2 = $map;
                $map['p_deliver_cate'] = ['in','1,3'];
                $map2['shop_qu_id'] = $area;
            }
            $order = 'p_m_team_can_status desc,p_m_team_nums asc';
        }
        if($flag == true){
            if(isset($area) && $area){
                $map2 = $map;
                $map['p_deliver_cate'] = ['in','1,3'];
                $map2['shop_qu_id'] = $area;
            }
        }
        $field = 'p_id,p_name,p_banner,p_now_price,p_give,p_model,p_m_team_remark';
        $field .= ',p_m_team_status,p_m_single_one_money,p_m_single_one_jifen,p_m_single_two';
        $field .= ',p_m_team_nums,p_m_team_join_money,p_m_team_join_jifen,p_m_team_can_status,p_m_team_can_endtime';
        $field .= ',p_m_team_leader_money,p_m_team_leader_jifen';
        if($map2){
            $data = Db::table('up_product p')
                ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                ->where(function ($query) use ($map) {
                    $query->where($map);
                })
                ->whereOr(function ($query) use ($map2) {
                    $query->where($map2);
                })
                ->field($field)
                ->order($order)
                ->page($page,10)
                ->select();
        }else{
            $data = Db::table('up_product p')
                ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                ->where($map)
                ->field($field)
                ->order($order)
                ->page($page,10)
                ->select();
        }
        if($data){
            $data = $this->handleGoodsInfo($data,$user_id,$store_uid);
        }
        return json(['status'=>200,'msg'=>$data]);
    }


    /**
     * 用户看我的小店（扫码进入）
     * @return \think\response\Json
     */
    public function seeStoreGoods(){
        extract (input());
        $store = $this->getUserInfo($uid,'user_m_name,user_m_logo,user_m_desc',2);
        $map = [
            'p_status' => 4,
            'p_type' => 1,
            'p_m_pool' => 3,
        ];
        $field = 'p_id,p_name,p_banner,p_now_price,p_give,p_model,p_m_team_remark';
        $field .= ',p_m_team_status,p_m_single_one_money,p_m_single_one_jifen,p_m_single_two';
        $field .= ',p_m_team_nums,p_m_team_join_money,p_m_team_join_jifen,p_m_team_can_status,p_m_team_can_endtime';
        $ones = Db::table('up_m_goods g')
            ->join('up_product p','g.good_p_id = p.p_id','left')
            ->where('good_user_id',$uid)
            ->where('p_m_team_status',2)
            ->where($map)
            ->field($field)
            ->select();
        if($ones){
            $ones = $this->handleGoodsInfo($ones,$user_id);
        }
        $teams = Db::table('up_m_goods g')
            ->join('up_product p','g.good_p_id = p.p_id','left')
            ->where('good_user_id',$uid)
            ->where('p_m_team_status',1)
            ->where($map)
            ->field($field)
            ->page(1,1)
            ->select();
        if($teams){
            $teams = $this->handleGoodsInfo($teams,$user_id,$uid);
        }
        return json(['status'=>200,'msg'=>$store,'ones'=>$ones,'teams'=>$teams]);
    }

    /**
     * 用户看我的小店之全部团团赚商品（扫码进入）
     * @return \think\response\Json
     */
    public function seeStoreCanTeamGoods(){
        extract (input());
        $image = $this->getConfigInfo(46);
        $map = [
            'p_status' => 4,
            'p_type' => 1,
            'p_m_pool' => 3,
            'p_m_team_status' => 1,
        ];
        $field = 'p_id,p_name,p_banner,p_now_price,p_give,p_model,p_m_team_remark';
        $field .= ',p_m_team_status,p_m_single_one_money,p_m_single_one_jifen,p_m_single_two';
        $field .= ',p_m_team_nums,p_m_team_join_money,p_m_team_join_jifen,p_m_team_can_status,p_m_team_can_endtime';
        $store_uid = '';
        if(isset($uid) && $uid){
            $store_uid = $uid;
            $map['good_user_id'] = $uid;
            $teams = Db::table('up_m_goods g')
                ->join('up_product p','g.good_p_id = p.p_id','left')
                ->where($map)
                ->field($field)
                ->order('good_team_status desc,p_m_team_nums asc')
                ->page($page,10)
                ->select();
        }else{
            $teams = Db::table('up_product')
                ->where($map)
                ->field($field)
                ->order('p_m_team_can_status desc,p_m_team_nums asc')
                ->page($page,10)
                ->select();
        }
        if($teams){
            $teams = $this->handleGoodsInfo($teams,$user_id,$store_uid);
        }
        return json(['status'=>200,'msg'=>$image,'teams'=>$teams]);
    }

    /**
     * 添加商品进我的小店
     * @return \think\response\Json
     */
    public function addGoodStore(){
        extract (input());
        $user = $this->getUserInfo($user_id,'user_level,user_m_open',2);
        if($user['user_level'] > 1 && $user['user_m_open'] == 2) {
            $have = Db::table('up_m_goods')
                ->where('good_user_id',$user_id)
                ->where('good_p_id',$p_id)
                ->find();
            if($have){
                return json(['status'=>100,'msg'=>'已经添加过了']);
            }
            $data = Db::name('product')
                ->where('p_id',$p_id)
                ->field('p_shop_id,p_status')
                ->find();
            $insert = [
                'good_p_id' => $p_id,
                'good_shop_id' => $data['p_shop_id'],
                'good_user_id' => $user_id,
                'good_time' => $this->todayTime,
                'good_update' => $this->todayTime
            ];
            $res = Db::table('up_m_goods')->insert($insert);
            if($res){
                return json(['status'=>200,'msg'=>'添加成功']);
            }else{
                return json(['status'=>100,'msg'=>'添加失败，请刷新重试！']);
            }
        }else{
            return json(['status'=>100,'msg'=>'您还没有开启小店！']);
        }

    }
    /**
     * 删除我的小店的商品
     * @return \think\response\Json
     */
    public function delGoodStore(){
        extract (input());
        $have = Db::name('m_order')
            ->where('mo_status',1)
            ->where('mo_store_uid',$user_id)
            ->where('mo_p_id',$p_id)
            ->count();
        if($have > 0){
            return json(['status'=>100,'msg'=>'有未完成的团团赚，不能删除']);
        }
        $res = Db::table('up_m_goods')
            ->where('good_user_id',$user_id)
            ->where('good_p_id',$p_id)
            ->delete();
        if($res){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>100,'msg'=>'删除失败，请刷新重试！']);
        }
    }

    /**
     * 商品详情
     * uid存在是店主从自己的店看或者扫码进来的
     * @return \think\response\Json
     */
    public function goodsDetail(){
        extract (input());
//        $user_id=1;$p_id=3705;$area=1135;$uid=1;
        $user = $this->getUserInfo($user_id,'user_level,user_m_open',2);
        $goods = Db::name('product p')
            ->where(['p_id'=>$p_id])
            ->find();
//        $goods['monthSales'] = Db::table('up_order o')
//            ->join('up_order_info oi','oi.oi_order_id = o.o_id','left')
//            ->where(['oi_goods_id'=>$p_id,'o_pay_status'=>2])
////            ->whereTime('o_add_time','month')
//            ->sum ('oi_num');
        $goods['monthSales'] = $goods['p_sell_yet'];
        Db::name('shop')->where(['shop_id'=>$goods['p_shop_id']])->setInc ('shop_browse');
        $goods['have'] = 0; //无需展示加入小店，此值下不展示佣金情况，只展示p_give
        if($user['user_level'] > 1){ //需展示加入小店，此值下展示佣金情况，不展示评论和推荐
            $have = Db::table('up_m_goods')
                ->where('good_user_id',$user_id)
                ->where('good_p_id',$p_id)
                ->field('good_id')
                ->find();
            $goods['have'] = 1; //未加入小店
            if($have){
                $goods['have'] = 2; //已加入小店
            }
        }
        // 6个推荐
        if(isset($uid) && $uid){
            $goods['kefuPhone'] = Db::table('up_u_user')->where('user_id',$uid)->value('user_phone');
            $storeUid = $uid;
            $arr = Db::table('up_m_goods mg')
                ->join('up_product p','mg.good_p_id = p.p_id','left')
                ->where(['good_user_id'=>$uid,'p.p_status'=>4])
                ->field('good_user_id,p.p_id,p.p_banner,p.p_name')
                ->limit(6)
                ->order('p.p_attestation_time desc')
                ->select ();
        }else{
            $goods['kefuPhone'] = Db::name('shop')->where(['shop_id'=>$goods['p_shop_id']])->value ('shop_account');
            $storeUid = 0;
            $arr = Db::table('up_product')
                ->where(['p_status' => 4, 'p_type' => 1, 'p_m_pool' => 3])
                ->field('p_id,p_banner,p_name')
                ->limit(6)
                ->order('p_attestation_time desc')
                ->select ();
        }
        if($arr){
            foreach ($arr as $k => $v){
                //图片
                if($v['p_banner']){
                    $arr[$k]['p_banner'] = explode(',',$v['p_banner'])[0];
                }else{
                    $arr[$k]['p_banner'] = [];
                }
            }
        }
        $count = Db::name('appraise')
            ->where(['app_p_id'=>$p_id])
            ->count();
        $first = Db::name('appraise a')
            ->join('u_user u','a.app_user_id = u.user_id','left')
            ->where(['app_p_id'=>$p_id])
            ->page(1,3)
            ->field('a.*,u.user_username,u.user_image')
            ->select();
        $model = [];
        if($goods['p_model'] == 2){
            $model = Db::name('product_model')
                ->where(['m_product_id'=>$p_id])
                ->select ();
            $num = 0;
            foreach ($model as $key => $vo) {
                $num += $vo['m_num'];
            }
            $goods['p_stock_num'] = $num;
        }
        //如果是团团赚，额外有团团赚的推荐和产品展示, 是小店里的团团赚还是首页里的团团赚
        //如果是团团赚，$team绝不为空
        $team = [];
        $team_tuijian = [];
        if($goods['p_m_team_status'] == 1){
            //当前情况
            $teamcount = Db::name('m_order')
                ->where('mo_store_uid',$storeUid)
                ->where('mo_p_id',$p_id)
                ->where('mo_status',1)
                ->where('mo_pay_status',2)
                ->column('mo_user_id');
            $team['need_num'] = $goods['p_m_team_nums'];
            $team['join_num'] = count($teamcount);
            $team['users'] = [];
            if($teamcount){
                $team['users'] = Db::name('u_user')->where('user_id', 'in',$teamcount)->column('user_image');
            }
            //推荐数据
            $where = [
                'mo_store_uid' => $storeUid,
                'mo_p_id' => ['<>',$p_id],
                'mo_status' => 1,
                'mo_pay_status' => 2
            ];
            $where2 = [];
            if(isset($area) && $area){
                $where2 = $where;
                $where['p_deliver_cate'] = ['in','1,3'];
                $where2['shop_qu_id'] = $area;
            }
            if($where2){
                $tj_data = Db::name('m_order mo')
                    ->join('up_product p','mo.mo_p_id = p.p_id','left')
                    ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                    ->where(function ($query) use ($where) {
                        $query->where($where);
                    })
                    ->whereOr(function ($query) use ($where2) {
                        $query->where($where2);
                    })
                    ->group('mo_team_count')
                    ->order('havenums desc')
                    ->page(1,3)
                    ->field('count(*) havenums,mo_p_id,mo_goods_name,mo_goods_image,mo_store_uid,mo_team_count,p_m_team_nums,p_m_team_can_endtime,p_id,p_name,p_banner')
                    ->select();
            }else{
                $tj_data = Db::name('m_order mo')
                    ->join('up_product p','mo.mo_p_id = p.p_id','left')
                    ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                    ->where($where)
                    ->group('mo_team_count')
                    ->order('havenums desc')
                    ->page(1,3)
                    ->field('count(*) havenums,mo_p_id,mo_goods_name,mo_goods_image,mo_store_uid,mo_team_count,p_m_team_nums,p_m_team_can_endtime,p_id,p_name,p_banner')
                    ->select();
            }
            if($tj_data){
                foreach ($tj_data as $k => $v){
                    $haveUsers = Db::name('m_order')
                        ->where('mo_pay_status', 2)
                        ->where('mo_store_uid', $v['mo_store_uid'])
                        ->where('mo_p_id', $v['mo_p_id'])
                        ->where('mo_team_count', $v['mo_team_count'])
                        ->column('mo_user_id');
                    $tj_data[$k]['users'] = Db::name('u_user')->where('user_id', 'in',$haveUsers)->column('user_image');
                    $tj_data[$k]['need'] = $v['p_m_team_nums'] - count($haveUsers); //还差几人成团
                    //1、进行中算下结束时间
                    if($v['mo_store_uid'] > 0){
                        $last = Db::name('m_goods')
                            ->where('good_user_id', $v['mo_store_uid'])
                            ->where('good_p_id', $v['mo_p_id'])
                            ->field('good_team_status,good_team_end_time')
                            ->find();
                        $tj_data[$k]['endTime'] = $last['good_team_end_time']; //结束时间
                    }else{
                        $tj_data[$k]['endTime'] = $v['p_m_team_can_endtime']; //结束时间
                    }
                }
            }
            $tj_data2 = [[]];
            if(count($tj_data) < 3){
                if($storeUid > 0){
                    $where = [
                        'good_user_id' => $storeUid,
                        'good_p_id' => ['<>',$p_id],
                        'good_team_status' => 1,
                        'p_status' => 4,
                        'p_m_team_status' => 1
                    ];
                    $where2 = [];
                    if(isset($area) && $area){
                        $where2 = $where;
                        $where['p_deliver_cate'] = ['in','1,3'];
                        $where2['shop_qu_id'] = $area;
                    }
                    if($where2){
                        $tj_data2 = Db::table('up_m_goods mg')
                            ->join('up_product p','mg.good_p_id = p.p_id','left')
                            ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                            ->where(function ($query) use ($where) {
                                $query->where($where);
                            })
                            ->whereOr(function ($query) use ($where2) {
                                $query->where($where2);
                            })
                            ->order('good_team_status desc,p_m_team_nums asc')
                            ->page(1,3 - count($tj_data))
                            ->field('p_id,p_name,p_banner,p_m_team_nums')
                            ->select();
                    }else{
                        $tj_data2 = Db::table('up_m_goods mg')
                            ->join('up_product p','mg.good_p_id = p.p_id','left')
                            ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                            ->where($where)
                            ->order('good_team_status desc,p_m_team_nums asc')
                            ->page(1,3 - count($tj_data))
                            ->field('p_id,p_name,p_banner,p_m_team_nums')
                            ->select();
                    }

                }else{
                    $where = [
                        'p_type' => 1,
                        'p_status' => 4,
                        'p_m_pool' => 3,
                        'p_m_team_can_status' => 1,
                        'p_id' => ['<>',$p_id],
                        'p_m_team_status' => 1
                    ];
                    $where2 = [];
                    if(isset($area) && $area){
                        $where2 = $where;
                        $where['p_deliver_cate'] = ['in','1,3'];
                        $where2['shop_qu_id'] = $area;
                    }
                    if($where2){
                        $tj_data2 = Db::table('up_product p')
                            ->join('up_shop s','p.p_shop_id = s.shop_id','left')
                            ->where(function ($query) use ($where) {
                                $query->where($where);
                            })
                            ->whereOr(function ($query) use ($where2) {
                                $query->where($where2);
                            })
                            ->order('p_m_team_can_status desc,p_m_team_nums asc')
                            ->page(1,3 - count($tj_data))
                            ->field('p_id,p_name,p_banner,p_m_team_nums')
                            ->select();
                    }else{
                        $tj_data2 = Db::table('up_product')
                            ->where($where)
                            ->order('p_m_team_can_status desc,p_m_team_nums asc')
                            ->page(1,3 - count($tj_data))
                            ->field('p_id,p_name,p_banner,p_m_team_nums')
                            ->select();
                    }

                }
                if($tj_data2){
                    foreach ($tj_data2 as $k => $v){
                        $tj_data2[$k]['havenums'] = $v['p_m_team_nums'];
                        $tj_data2[$k]['mo_p_id'] = $v['p_id'];
                        $tj_data2[$k]['mo_goods_name'] = $v['p_name'];
                        $tj_data2[$k]['mo_goods_image'] = $v['p_banner'] ? explode(',',$v['p_banner'])[0] : '';
                        $tj_data2[$k]['mo_store_uid'] = $storeUid;
                        $tj_data2[$k]['mo_team_count'] = '';
                        $tj_data2[$k]['p_m_team_can_endtime'] = '';
                        $tj_data2[$k]['users'] = ''; //users为空说明没人，不需要结束时间和头像
                        $tj_data2[$k]['need'] = $v['p_m_team_nums'];
                        $tj_data2[$k]['endTime'] = '';
                    }
                }
            }
            $team_tuijian = array_merge($tj_data,$tj_data2);
        }
        return json([
            'status'=>200,'msg'=>$goods,'arr'=>$arr,'count'=>$count,'first'=>$first,'model'=>$model
            ,'team'=>$team,'team_tuijian'=>$team_tuijian
        ]);
    }

    /**
     * 商品评价
     * @return \think\response\Json
     */
    public function goodsAppraise(){
        extract (input ());
        $where = [
            'app_p_id'=>$p_id
        ];
        if(isset($type) && $type){
            switch ($type){
                case 1:
                    $where['app_imgs'] = ['neq',''];
                    break;
                case 2:
                    $where['app_type'] = ['in','4,5'];
                    break;
                case 3:
                    $where['app_type'] = 3;
                    break;
                case 4:
                    $where['app_type'] = ['in','1,2'];
                    break;
            }
        }
        $data = Db::name('appraise a')
            ->join('u_user u','a.app_user_id = u.user_id','left')
            ->where($where)
            ->field('a.*,u.user_username,u.user_image')
            ->page($page,10)
            ->order('app_time desc')
            ->select ();
        return json(['status'=>200,'msg'=>$data]);
    }

    /**
     * 先生成订单，再支付，支付在user的paymoney
     * @return \think\response\Json
     */
    public function doMath(){
        extract (input());
        $order = [];
        Db::startTrans ();
        try{
            $good = Db::name ('product')->where ('p_id' , $p_id)->find ();
            $info = Db::name ('shop')->where ('shop_id' , $good['p_shop_id'])->find ();
            $j_order1 = $this->getOrderNumber ();
            $p_postage = 0;
            if($good['p_postage']){
                $p_postage = $good['p_postage'];
            }
            $j_param1 = [
                'o_type' => 2 ,
                'o_user_id' => $user_id ,
                'o_order_num' => $j_order1 ,
                'o_money' => $price + $p_postage,
                'o_m_money' => $good['p_m_single_all_money'],
                'o_status' => 1 ,
                'o_pay_status' => 1 ,
                'o_shop_id' => $good['p_shop_id'] ,
                'o_shop_name' => $info[ 'shop_name' ] ,
                'o_cate' => $good['p_deliver_cate'] ,
                'o_postage' => $good['p_postage'] ? $good['p_postage'] : '' ,
                'o_m_type' => 2 ,
                'o_m_user_id' => $uid ? $uid : 0,
                'o_add_time' => date ("Y-m-d H:i:s") ,
                'o_lose_time' => date ('Y-m-d H:i:s' , strtotime ('+1 day'))
            ];
            if($good['p_deliver_cate'] == 2 || $good['p_deliver_cate'] == 4){
                $j_param1['o_qrcode'] = "https://csdl.jintianjifen.cn/api/shop/scanQrcodeOrder?num=" . $j_order1;
            }
            if($good['p_deliver_cate'] == 1 || $good['p_deliver_cate'] == 3){
                $j_param1['o_name'] = $name;
                $j_param1['o_phone'] = $phone;
                $j_param1['o_address'] = $address;
            }
            $j_get_id1 = Db::name('order')->insertGetId ($j_param1);
            $j_info_param1 = [
                'oi_order_id' => $j_get_id1 ,
                'oi_goods_id' => $p_id ,
                'oi_goods_name' => $good['p_name'] ,
                'oi_goods_image' => $good['p_banner'] ? explode(',',$good['p_banner'])[0] : '',
                'oi_goods_price' => $good['p_now_price'] ,
                'oi_goods_model' => $m_name , //规格名字
                'oi_num' => 1 ,
                'oi_total_price' => $good['p_now_price'] ,
                'oi_total_jifen' => 0
            ];
            Db::name('order_info')->insert ($j_info_param1);
            $order[] = $j_order1;
            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>'您的订单，下单成功！','n_images'=>'','n_type'=>2,'n_user_id'=>$user_id,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);

            try{
                $this->jpushUser(1,$user_id,'您的订单，下单成功！',json([]));
            }catch (\Exception $e){
                Log::record($e->getMessage(),'error');
            }

            Db::commit ();
            return json(['status'=>200,'msg'=>$j_order1,'order'=>$j_order1]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'下单失败']);
        }

    }
    /**
     * 团购订单处理
     * @return \think\response\Json
     */
    public function teamPay(){
        extract (input());
//        $p_id = 2302;
//        $user_id = 1;
//        $uid = 1;
//        $price = 33.9;
//        $name = '名字';
//        $phone = '18688886666';
//        $address = '地址地址地址地址地址地址地址';
//        $m_name = '绿色';
        if(!$uid){
            $uid = 0;
        }
        $getOrderUser = Db::name('m_order')
            ->where('mo_status',1)
            ->where('mo_pay_status',2)
            ->where('mo_store_uid',$uid)
            ->where('mo_p_id',$p_id)
            ->where('mo_user_id',$user_id)
            ->find();
        if($getOrderUser){
            return json(['status'=>100,'msg'=>'您已经参与此期团团赚了，请耐心等待开奖~']);
        }
        Db::startTrans ();
        try{
            $good = Db::name ('product')->where ('p_id' , $p_id)->find ();
            if($good['p_m_team_status'] == 2){
                return json(['status'=>100,'msg'=>'此商品已关闭团团赚~']);
            }
            $info = Db::name ('shop')->where ('shop_id' , $good['p_shop_id'])->find ();
            $j_order1 = $this->getOrderNumber ();
            $p_postage = 0;
            if($good['p_postage']){
                $p_postage = $good['p_postage'];
            }
            $j_param1 = [
                'mo_order_num' => $j_order1 ,
                'mo_p_id' => $p_id ,
                'mo_store_uid' => $uid ? $uid : 0,
                'mo_user_id' => $user_id ,
                'mo_money' => $price + $p_postage,
                'mo_team_money' => $good['p_m_team_all_money'],
                'mo_status' => 1 ,
                'mo_pay_type' => $type ,
                'mo_pay_status' => 1 ,
                'mo_get_user_id' => '' ,
                'mo_shop_id' => $good['p_shop_id'] ,
                'mo_shop_name' => $info[ 'shop_name' ] ,
                'mo_cate' => $good['p_deliver_cate'] ,
                'mo_postage' => $good['p_postage'] ? $good['p_postage'] : '' ,
                'mo_goods_name' => $good['p_name'] ,
                'mo_goods_image' => $good['p_banner'] ? explode(',',$good['p_banner'])[0] : '',
                'mo_goods_price' => $good['p_now_price'] ,
                'mo_goods_model' => $m_name ,
                'mo_time' => date ("Y-m-d H:i:s")
            ];
            if($good['p_deliver_cate'] == 2 || $good['p_deliver_cate'] == 4){
                $j_param1['mo_qrcode'] = "https://csdl.jintianjifen.cn/api/shop/scanQrcodeOrder?num=" . $j_order1;
            }
            if($good['p_deliver_cate'] == 1 || $good['p_deliver_cate'] == 3){
                $j_param1['mo_name'] = $name;
                $j_param1['mo_phone'] = $phone;
                $j_param1['mo_address'] = $address;
            }
            Db::name('m_order')->insert($j_param1);
            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>'您的订单，下单成功！','n_images'=>'','n_type'=>2,'n_user_id'=>$user_id,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
            try{
                $this->jpushUser(1,$user_id,'您的订单，下单成功！',json([]));
            }catch (\Exception $e){
                Log::record($e->getMessage(),'error');
            }
            Db::commit ();
            $money = $j_param1['mo_money'];
            if(isset($miniCode)){
                $openid = $this->getOpenId($miniCode);
                if($openid == ''){
                    return json(['status'=>100,'msg'=>'支付失败']);
                }
                $wx = new Wechat();
                $obj = [
                    'attach'=>"payMoneyTeam",
                    'body'=>"团购订单支付",
                    'total_fee'=>$money * 100,
                    'out_trade_no'=>$j_order1,
                    'product_id'=>"",
                    'trade_type'=>"JSAPI",
                    'openid'       => $openid
                ];
                $res = $wx->WeChatPayReady($obj);
                return json(['status'=>200,'msg'=>$res]);
            }
            if($type == 1){
                $ali = new Ali();
                $res = $ali->getParam($j_order1,$money,'payMoneyTeam','团购订单支付');
            }else{
                $wx = new Weixin();
                $obj = [
                    'attach'=>"payMoneyTeam",
                    'body'=>"团购订单支付",
                    'total_fee'=>$money * 100,
                    'out_trade_no'=>$j_order1,
                    'product_id'=>"",
                    'trade_type'=>"APP"
                ];
                $res = $wx->WeChatPayReady($obj);
            }
            return json(['status'=>200,'msg'=>$res]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'下单失败']);
        }

    }

    /**
     * 我的团队
     */
    public function myTeams()
    {
        extract (input());
        $data = Db::name('u_user')
            ->where('user_level', '>',1)
            ->where('user_recommend', $user_id)
            ->field('user_id,user_username,user_image,user_level')
            ->page($page,10)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                $data[$k]['todayMoney'] = Db::name('order')
                    ->where('o_m_user_id', $v['user_id'])
                    ->where('o_pay_status', 2)
                    ->where('o_m_type', 2)
                    ->whereTime('o_add_time', 'today')
                    ->sum('o_money');
            }
        }
        return json(['status' => 200,'msg' => $data]);
    }
    /**
     * 看我的团队的订单
     */
    public function myTeamsOrder()
    {
        extract (input());
        $data = Db::table('up_order')->alias('o')
            ->join('up_order_info oi','o.o_id = oi.oi_order_id','left')
            ->join('up_u_user u','o.o_user_id = u.user_id','left')
            ->where('o_m_user_id', $uid)
            ->where('o_pay_status', 2)
            ->where('o_m_type', 2)
            ->whereTime('o_add_time', 'today')
            ->field('o_id,user_username,user_image,o_add_time,oi.*')
            ->order('o_add_time desc')
            ->page($page,10)
            ->select();
        return json(['status' => 200,'msg' => $data]);
    }
    /**
     * 店主看我店里的订单或用户看我的订单
     * type：1销售订单  2团团赚订单
     * 已确认收货了的话就是已送，未收货看o_qrcode，为空是收货，不为空是核销
     * record_from_type为4是二级分销，店主是o_shop_name
     */
    public function myPoolStoreOrders()
    {
        extract (input());
        $user = $this->getUserInfo($user_id,'user_m_pool_money',2);
        $money = [];
        $money['all_money'] = $user['user_m_pool_money'];
        $money['will_money'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->where('record_status',1)
            ->sum('record_money');
        $money['all_jifen'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->sum('record_jifen');
        $money['will_jifen'] = Db::table('up_m_record')
            ->where('record_user_id',$user_id)
            ->where('record_status',1)
            ->sum('record_jifen');
        if($type == 1){
            $data = Db::table('up_m_record')->alias('m')
                ->join('up_order o','m.record_order_number = o.o_order_num','left')
                ->join('up_order_info oi','o.o_id = oi.oi_order_id','left')
                ->join('up_u_user u','o.o_user_id = u.user_id','left')
                ->where('record_user_id', $user_id)
                ->where('record_type', 1)
                ->where('record_from_type', 'in','1,3,4')
                ->field('o_id,user_username,user_image,o_add_time,o_qrcode,o_shop_name,oi.*,record_from_type,record_status,record_jifen,record_money')
                ->order('o_add_time desc')
                ->page($page,10)
                ->select();
        }else{
            $where = [
                'mo_user_id|mo_store_uid' => $user_id,
                'mo_pay_status' => 2
            ];
            $field = 'mo_time,mo_goods_name,mo_goods_image,mo_goods_price,mo_goods_model';
            $field .= ',mo_status,mo_qrcode,mo_cate,mo_get_user_id';
            $field .= ',mo_store_uid,mo_p_id,mo_team_count,p_m_team_nums,p_m_team_can_endtime';
            $data = Db::table('up_m_order')->alias('mo')
                ->join('up_product p','mo.mo_p_id = p.p_id','left')
                ->where( $where)
                ->group('mo_p_id,mo_store_uid,mo_team_count')
                ->field($field)
                ->order('mo_time desc')
                ->page($page,10)
                ->select();
            foreach ($data as $k => $v){
                if($v['mo_store_uid'] && $v['mo_store_uid'] > 0){
                    $storeName = Db::name('u_user')->where('user_id', $v['mo_store_uid'])->value('user_username');
                    $data[$k]['storeName'] = $storeName . '的小店';
                }else{
                    $data[$k]['storeName'] = '产品池';
                }
                $haveUsers = Db::name('m_order')
                    ->where('mo_pay_status', 2)
                    ->where('mo_store_uid', $v['mo_store_uid'])
                    ->where('mo_p_id', $v['mo_p_id'])
                    ->where('mo_team_count', $v['mo_team_count'])
                    ->column('mo_user_id');
                $data[$k]['users'] = Db::name('u_user')->where('user_id', 'in',$haveUsers)->column('user_image');
                $data[$k]['need'] = $v['p_m_team_nums'] - count($haveUsers); //还差几人成团
                //1、进行中算下结束时间
                if($v['mo_status'] == 1){
                    if($v['mo_store_uid'] > 0){
                        $last = Db::name('m_goods')
                            ->where('good_user_id', $v['mo_store_uid'])
                            ->where('good_p_id', $v['mo_p_id'])
                            ->field('good_team_status,good_team_end_time')
                            ->find();
                        $data[$k]['endTime'] = $last['good_team_end_time']; //结束时间
                    }else{
                        $data[$k]['endTime'] = $v['p_m_team_can_endtime']; //结束时间
                    }
                }
                //2、已开奖算下奖励
                if($v['mo_status'] == 2){
                    $getOrderUser = Db::name('m_order mo')
                        ->join('u_user u','mo.mo_get_user_id = u.user_id','left')
                        ->where('mo_pay_status', 2)
                        ->where('mo_store_uid', $v['mo_store_uid'])
                        ->where('mo_p_id', $v['mo_p_id'])
                        ->where('mo_team_count', $v['mo_team_count'])
                        ->where('mo_user_id', $v['mo_get_user_id'])
                        ->field('mo_order_num,user_username,user_image')
                        ->find();
                    $dataMJ = Db::name('m_record')
                        ->where('record_order_number', $getOrderUser['mo_order_num'])
                        ->where('record_user_id', $user_id)
                        ->where('record_type', 2)
                        ->where('record_from_type', 'in','2,7,8')
                        ->field('sum(record_jifen) jifen,sum(record_money) money')
                        ->find();
                    $data[$k]['priceUname'] = $getOrderUser['user_username'];
                    $data[$k]['priceUimg'] = $getOrderUser['user_image'];
                    $data[$k]['priceMoney'] = $dataMJ['money'];
                    $data[$k]['priceJifen'] = $dataMJ['jifen'];
                }
            }
        }
        //1显示提现  2关闭提现
        return json(['status'=>200,'msg'=>$data,'money'=>$money,'cashShow' => 2]);
    }

    //------------------------------提现----------------------------------------------------------------
    public function tixianRemark()
    {
        $conf = Db::name('jifen_conf')->where(['conf_id'=>['in','29,30,31,47']])->column ('conf_rate');

        return json(['status' => 200 , 'msg' => $conf[3], 'min' => $conf[0]]);
    }
    public function takeCash(){
        extract (input());
        //小程序获取openID
        if(isset($mini,$type,$user_id,$openid) && $type == 2){
            $type = 3;
            $use_open_id = $this->getUserInfo($user_id,'user_open_id');
            if(!empty($use_open_id)){
                $openid = $use_open_id;
            }else{
                //通过code获取openID
                $use_open_id = $this->getOpenId($openid);
                if(empty($use_open_id)){
                    return json(['status'=>100,'msg'=>'缺少微信openid']);
                }
                //更新用户openID
                Db::name('u_user')->where(['user_id'=>$user_id])->setField('user_open_id',$use_open_id);
                $openid = $use_open_id;
            }
        }
        if($real_name == '张秀平' || $real_name == '高兴兰'){
            return json(['status' => 100, 'msg' => '您的账号异常，不能提现，请联系管理员！']);
        }
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        $phone = $this->getUserInfo($user_id,'user_phone');
        $phone_code = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0,'type'=>1])->find();
        if(empty($phone_code)){
            return json(['status'=>100,'msg'=>'请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if($diff >= 30*60){
            return json(['status'=>100,'msg'=>'验证码已失效']);
        }
        if($code != $phone_code['code']){
            return json(['status'=>100,'msg'=>'验证码输入错误']);
        }
        $is_have = Db::name('m_order_tixian')->where(['o_user_id'=>$user_id,'o_tixian_status'=>1])->count();
        if($is_have > 0){
            return json(['status'=>100,'msg'=>'您有待审核提现']);
        }
        $is_have2 = Db::name('m_order_tixian')
            ->where(['o_user_id'=>$user_id])
            ->whereTime('o_add_time','today')
            ->count();
        if($is_have2 >= 2){
            return json(['status'=>100,'msg'=>'一天只能提现两次']);
        }
        $conf = Db::name('jifen_conf')->where(['conf_id'=>['in','29,30,31']])->column ('conf_rate');
        $user = Db::name('u_user')->where('user_id',$user_id)->find();
        if($type >= 2 && isset($openid) && $openid == ''){
            return json(['status'=>100,'msg'=>'缺少微信openid']);
        }
        if ($user['user_m_pool_money'] <= 0) {
            return json(['status'=>100,'msg'=>'可提现金额不足']);
        }
        if($money > $user['user_m_pool_money']){
            return json(['status'=>100,'msg'=>'提现金额大于可提现金额']);
        }
        if($user['user_m_pool_money'] < $conf[0]){
            return json(['status'=>100,'msg'=>'可提现金额低于最低提现金额']);
        }
        if($money < $conf[0]){
            return json(['status'=>100,'msg'=>'提现金额低于最低提现金额']);
        }
        $number = $this->getOrderNumber ();
        $new_money = $money - ($money * $conf[1]);
        $param = [
            'o_user_id'=>$user_id,
            'o_order_num'=>$number,
            'o_money'=>$money,
            'o_account'=>$account,
            'o_real_name'=>$real_name,
            'o_pay_type'=>$type,
            'o_add_time'=>date('Y-m-d H:i:s')
        ];
        $havemoney = Db::name('m_order_tixian')
            ->where(['o_user_id'=>$user_id])
            ->where('o_tixian_status','in','1,2')
            ->whereTime('o_add_time','today')
            ->sum('o_money');
        if($havemoney + $money >= $conf[2]){
            Db::name('u_user')->where('user_id',$user_id)->setDec('user_m_pool_money',$money);

            $param['o_tixian_status'] = 1;
            if($type >= 2){
                $param['o_openid'] = $openid;
            }
            Db::name('m_order_tixian')->insert($param);
            return json(['status'=>200,'msg'=>'提交成功，已达每日最大提现限额，等待后台审核']);
        }else{
            if($type == 1){
                $ali = new Ali();
                $res = $ali->tixianAgreeShopOrWork($number,$new_money,$account,$real_name);
                $msg = '支付宝';
            }else if($type == 3){
                $wx = new Wechat();
                $res = $wx->userTiXian($number,$openid,$new_money,$real_name);
                $msg = '微信';
            }else{
                $wx = new Weixin();
                $res = $wx->userTiXian($number,$openid,$new_money,$real_name);
                $msg = '微信';
            }
            if($res['status'] == 200){
                $param['o_tixian_status'] = 2;
                $param['o_third_order_num'] = $res['msg'];
                Db::name('m_order_tixian')->insert($param);
                Db::name('u_user')->where('user_id',$user_id)->setDec('user_m_pool_money',$money);

                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'余额提现','n_content'=>'您提现了'.$money.'元'."，已提现至您的{$msg}账户，请注意查收！",'n_images'=>'','n_type'=>3,'n_user_id'=>$user_id,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                $this->jpushUser(1,$user_id,'您提现了'.$money.'元'."，已提现至您的{$msg}账户，请注意查收！",json([]));
                return json(['status'=>200,'msg'=>"已提现至您的{$msg}账户，请注意查收！"]);
            }else{
                return json(['status'=>100,'msg'=>$res['msg']]);
            }
        }
    }
    /**
     * 我的提现记录
     */
    public function myTixianOrder()
    {
        extract (input());
        $data = Db::name('m_order_tixian')
            ->where(['o_user_id'=>$user_id])
            ->order('o_add_time desc')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    //------------------------------海报----------------------------------------------------------------
    public function shopHaibao()
    {
        $uid = input('uid');
        $user = $this->getUserInfo($uid,'user_m_ercode,user_m_haibao1,user_m_haibao2,user_m_haibao3',2);
        $flag = true;
        if(!$user['user_m_haibao1']){
            $flag = false;
            $dst_path = './uploads/one.png';
            $logo = $user['user_m_ercode'];
            $url = $this->hecheng_pic($logo,$dst_path,$uid,1);
            Db::name('u_user')->where('user_id',$uid)->setField('user_m_haibao1',$url);
        }
        if(!$user['user_m_haibao2']){
            $flag = false;
            $dst_path = './uploads/two.png';
            $logo = $user['user_m_ercode'];
            $url = $this->hecheng_pic($logo,$dst_path,$uid,2);
            Db::name('u_user')->where('user_id',$uid)->setField('user_m_haibao2',$url);
        }
        if(!$user['user_m_haibao3']){
            $flag = false;
            $dst_path = './uploads/three.png';
            $logo = $user['user_m_ercode'];
            $url = $this->hecheng_pic($logo,$dst_path,$uid,3);
            Db::name('u_user')->where('user_id',$uid)->setField('user_m_haibao3',$url);
        }
        if($flag == false){
            $user = $this->getUserInfo($uid,'user_m_ercode,user_m_haibao1,user_m_haibao2,user_m_haibao3',2);
        }
        $rand = rand(1,3);
        return json(['status' => 200 , 'msg' => $user["user_m_haibao{$rand}"]]);
    }
    public function hecheng_pic($desurl,$srcurl,$uid,$ji)
    {
        //创建源图的实例
        $src = imagecreatefromstring(file_get_contents($srcurl));
        //创建点的实例
        $des = imagecreatefrompng($desurl);
        //获取点图片的宽高
        list($point_w, $point_h) = getimagesize($desurl);
        list($old_w, $old_h) = getimagesize($srcurl);
        //重点：png透明用这个函数
        $name = time() . '_' . $uid . $ji . '.png';
        // imagecopy($src, $des, 200, 0, 0, 0, $point_w, $point_h);
        imagecopyresampled($src,$des,  180, 650, 0, 0, 400, 400, $point_w, $point_h);
        imagepng($src, './uploads/images/' . $name);
        imagedestroy($src);
        imagedestroy($des);
        return "https://csdl.jintianjifen.cn/uploads/images/" . $name;
    }
    //-----------------------------------红包 start ---------------------------------------------
    /**
     * 我的红包
     */
    public function myRed()
    {
        extract (input());
        $data = Db::name('m_red')
            ->where(['red_user_id'=>$user_id,'red_status'=>2])
            ->order('red_add_time desc')
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的红包领取明细
     */
    public function myRedUsers()
    {
        extract (input());
        $data = Db::name('m_red_user')->alias('ru')
            ->join('u_user u', 'ru.ru_user_id = u.user_id')
            ->where(['ru_red_id'=>$red_id,'ru_status'=>2])
            ->order('ru_get_time desc')
            ->page($page,20)
            ->field('ru.*,user_username,user_image')
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 新建红包
     */
    public function myRedAdd()
    {
        extract (input());
        if($type == 1) return json(['status'=>100,'msg'=>'请使用微信充值']);
        $red_user_area = Db::name('partner')
            ->where('par_user_id',$user_id)
            ->value('par_qu_id');
        if(!$red_user_area){
            return json(['status'=>100,'msg'=>'您的身份有误，请联系管理员']);
        }
        if(mb_strlen($red_title) > 20){
            return json(['status'=>100,'msg'=>'广告设置不能多于20字']);
        }
        $insert = [
            'red_number' => $this->getOrderNumber (),
            'red_user_id' => $user_id,
            'red_user_area' => $red_user_area,
            'red_pay_type' => $type,
            'red_status' => 1,
            'red_type' => $red_type,
            'red_num' => $red_num,
            'red_money' => $red_money,
            'red_money_all' => $red_money,
            'red_title' => $red_title,
            'red_image' => $red_image,
            'red_add_time' => date('Y-m-d H:i:s')
        ];
        if($red_type == 1) $insert['red_money_all'] = $red_num * $red_money;
        $insert['red_money_all'] = floatval($insert['red_money_all']);
        if($insert['red_money_all'] / $red_num < 0.3){
            return json(['status'=>100,'msg'=>'金额太少，请重新输入金额！']);
        }
//        if($insert['red_money_all'] < 20){
//            return json(['status'=>100,'msg'=>'金额不能低于20！']);
//        }
        if($red_num < 1){
            return json(['status'=>100,'msg'=>'数量有误！']);
        }
        Db::startTrans ();
        try{
            $red_id = Db::name('m_red')->insertGetId($insert);
            //------------------
            $sons = [];
            $total = $insert['red_money_all'];
            $num = $red_num;
            $min = 0.3;
            for ($i=1;$i<=$num;$i++)
            {
                if($i == $num){
                    $sons[] = [
                        'ru_red_id' => $red_id,
                        'ru_user_id' => 0,
                        'ru_money' => $total,
                        'ru_status' => 1,
                        'ru_get_time' => date('Y-m-d H:i:s')
                    ];
                }else{
                    $safe_total=($total-(($num-$i)*$min))/($num-$i);//随机安全上限
                    if($safe_total < $min) $safe_total = $min;
                    $money=mt_rand($min*100,$safe_total*100)/100;
                    $total=$total-$money;
                    $sons[] = [
                        'ru_red_id' => $red_id,
                        'ru_user_id' => 0,
                        'ru_money' => $money,
                        'ru_status' => 1,
                        'ru_get_time' => date('Y-m-d H:i:s')
                    ];
                }
            }
            Db::name('m_red_user')->insertAll($sons);
            //------------------
            Db::commit ();
            $money = $insert['red_money_all'];
            $j_order1 = $insert['red_number'];
            $huidiaoRedAli = 'http://csdl.jintianjifen.cn/api/Ali/huidiaored';
            $huidiaoRedWx = 'http://csdl.jintianjifen.cn/api/Weixin/huidiaored';
            if(isset($miniCode)){
                $openid = $this->getOpenId($miniCode);
                if($openid == ''){
                    return json(['status'=>100,'msg'=>'支付失败']);
                }
                $wx = new Wechat();
                $obj = [
                    'attach'=>"red",
                    'body'=>"红包充值",
                    'total_fee'=>$money * 100,
                    'out_trade_no'=>$j_order1,
                    'product_id'=>"",
                    'trade_type'=>"JSAPI",
                    'openid'       => $openid
                ];
                $res = $wx->WeChatPayReady($obj,$huidiaoRedWx);
                return json(['status'=>200,'msg'=>$res]);
            }
            if($type == 1){
                $ali = new Ali();
                $res = $ali->getParam($j_order1,$money,'red','红包充值',$huidiaoRedAli);
            }else{
                $wx = new Weixin();
                $obj = [
                    'attach'=>"red",
                    'body'=>"红包充值",
                    'total_fee'=>$money * 100,
                    'out_trade_no'=>$j_order1,
                    'product_id'=>"",
                    'trade_type'=>"APP"
                ];
                $res = $wx->WeChatPayReady($obj,$huidiaoRedWx);
            }
            return json(['status'=>200,'msg'=>$res]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'下单失败']);
        }
    }
    //-----------------------------------红包  end ---------------------------------------------
    //------------------------------定时器----------------------------------------------------------------
    /**
     * 关于团团赚订单的定时器
     */
    public function teamOrderTimer()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 1800));
        //1-1：时间到了之后没有凑够人数的退还——有店的
        $where = [];
        $where['good_team_status'] = 2;
        $where['good_team_end_time'] = ['<=', $today];
        $field = 'good_id,good_p_id,good_user_id';
        $res = Db::table('up_m_goods')
            ->where($where)
            ->field($field)
            ->select();
//        dump($res);die;
        if ($res) {
            Db::startTrans();
            try {
                foreach ($res as $k => $v) {
                    Db::table('up_m_goods')->where('good_id',$v['good_id'])->inc('good_team_count',1)->update([
                        'good_team_status' => 1
                    ]);
                    $data = Db::table('up_m_order')
                        ->where('mo_p_id',$v['good_p_id'])
                        ->where('mo_store_uid',$v['good_user_id'])
                        ->where('mo_status',1)
                        ->where('mo_pay_status',2)
                        ->where('mo_back_status','in','1,3')
                        ->field('mo_id,mo_money,mo_order_num,mo_third_order_num,mo_pay_type')
                        ->select();
                    if($data){
                        foreach ($data as $k2 => $v2){
                            if($v2['mo_pay_type'] == 1){
                                $ali = new Ali();
                                $tuires = $ali->refund($v2['mo_third_order_num'],$v2['mo_money']);
                            }else{
                                $wx = new Weixin();
                                $tuires = $wx->weixiReturn($v2['mo_money'],$v2['mo_money'],$v2['mo_third_order_num'],$this->getOrderNumber ());
                            }
                            if($tuires['status'] == 100){
                                Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                    'mo_back_status' => 3,
                                    'mo_status' => 3,
                                    'mo_back_msg' => $tuires['msg']
                                ]);
                            }else{
                                Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                    'mo_back_status' => 2,
                                    'mo_status' => 3
                                ]);
                            }
                        }
                    }
                }
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                return 2;
            }
        }
        //1-2：时间到了之后没有凑够人数的退还——没店的
        $where = [];
        $where['p_m_team_status'] = 1;
        $where['p_m_team_can_status'] = 2;
        $where['p_m_team_can_endtime'] = ['<=', $today];
        $field = 'p_id';
        $res = Db::table('up_product')
            ->where($where)
            ->field($field)
            ->select();
        if ($res) {
            Db::startTrans();
            try {
                foreach ($res as $k => $v) {
                    Db::table('up_product')->where('p_id',$v['p_id'])->inc('p_m_team_count',1)->update([
                        'p_m_team_can_status' => 1
                    ]);
                    $data = Db::table('up_m_order')
                        ->where('mo_p_id',$v['p_id'])
                        ->where('mo_store_uid',0)
                        ->where('mo_status',1)
                        ->where('mo_pay_status',2)
                        ->where('mo_back_status','in','1,3')
                        ->field('mo_id,mo_money,mo_order_num,mo_third_order_num,mo_pay_type')
                        ->select();
                    if($data){
                        foreach ($data as $k2 => $v2){
                            if($v2['mo_pay_type'] == 1){
                                $ali = new Ali();
                                $tuires = $ali->refund($v2['mo_third_order_num'],$v2['mo_money']);
                            }else{
                                $wx = new Weixin();
                                $tuires = $wx->weixiReturn($v2['mo_money'],$v2['mo_money'],$v2['mo_third_order_num'],$this->getOrderNumber ());
                            }
                            if($tuires['status'] == 100){
                                Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                    'mo_back_status' => 3,
                                    'mo_status' => 3,
                                    'mo_back_msg' => $tuires['msg']
                                ]);
                            }else{
                                Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                    'mo_back_status' => 2,
                                    'mo_status' => 3
                                ]);
                            }
                        }
                    }
                }
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                return 2;
            }
        }
        //2：开奖了但是没中的
        $where = [];
        $where['mo_status'] = ['in','2,3'];
        $where['mo_pay_status'] = 2;
        $where['mo_back_status'] = ['in','1,3'];
        $field = 'mo_id,mo_money,mo_order_num,mo_third_order_num,mo_pay_type,mo_user_id,mo_get_user_id,mo_status';
        $res = Db::table('up_m_order')
            ->where($where)
            ->field($field)
            ->select();
        if ($res) {
            Db::startTrans();
            try {
                foreach ($res as $k2 => $v2){
                    if($v2['mo_user_id'] != $v2['mo_get_user_id']){
                        if($v2['mo_pay_type'] == 1){
                            $ali = new Ali();
                            $tuires = $ali->refund($v2['mo_third_order_num'],$v2['mo_money']);
                        }else{
                            $wx = new Weixin();
                            $tuires = $wx->weixiReturn($v2['mo_money'],$v2['mo_money'],$v2['mo_third_order_num'],$this->getOrderNumber ());
                        }
                        if($tuires['status'] == 100){
                            Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                'mo_back_status' => 3,
                                'mo_back_msg' => $tuires['msg']
                            ]);
                        }else{
                            Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                                'mo_back_status' => 2,
                            ]);
                        }
                    }else{
                        Db::table('up_m_order')->where('mo_id',$v2['mo_id'])->update([
                            'mo_back_status' => 2,
                        ]);
                    }
                }
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                return 2;
            }
        }
        //3：产品池和团团赚的商家的余额问题,只要入的时候扣掉，然后确认收货时校验的时候去掉
//        $where = [];
//        $where['o_m_type'] = ['in','2,3'];
//        $where['o_pay_status'] = 2;
//        $where['o_m_less'] = 1;
//        $field = 'o_shop_id,o_m_money';
//        $res = Db::table('up_order')
//            ->where($where)
//            ->field($field)
//            ->select();
//        if ($res) {
//            Db::startTrans();
//            try {
//                foreach ($res as $k2 => $v2){
//                    Db::name('shop')->where('shop_id', $v2['o_shop_id'])->setDec('shop_balance_yet', $v2['o_m_money']);
//                }
//                Db::commit();
//                return 1;
//            } catch (\Exception $e) {
//                Db::rollback();
//                return 2;
//            }
//        }
    }
    public function teamCanButNo()
    {
        set_time_limit(0);
        $map = [
            'p_status' => 4,
            'p_type' => 1,
            'p_m_pool' => 3,
        ];
        $data = DB::name('product')->alias('p')
            ->join('m_order mo','p.p_id = mo.mo_p_id','left')
            ->where($map)
            ->where('mo_pay_status',2)
            ->where('mo_status',1)
            ->group('mo_store_uid,mo_p_id')
            ->having('numsnums >= 2')
            ->field('p.*,mo.*,count(*) numsnums')
            ->select();
        $mww = input('mww');
        if(isset($mww) && $mww == 1){
            dump($data);die;
        }
        if($data){
            Db::startTrans ();
            try{
                $b = new Base();
                foreach ($data as $kk => $vv){
                    if($vv['p_m_team_nums'] <= $vv['numsnums']){ //这个团团赚人数已购，但是没有开奖。。。。
                        $info = $vv;
                        $one_good = Db::name('product')->where('p_id', $info['mo_p_id'])->find();
                        $oi_goods_name = $info['mo_goods_name'];
                        $haveUsersData = Db::name('m_order')
                            ->where('mo_status', 1)
                            ->where('mo_pay_status', 2)
                            ->where('mo_store_uid', $info['mo_store_uid'])
                            ->where('mo_p_id', $info['mo_p_id'])
                            ->select();
                        $o_status = in_array($info['mo_cate'], [1, 3]) ? 2 : 10;
                        //开奖啦
                        //1、先把自己的改为已开奖
                        //2、再把其他的改为已开奖(挪到第4一起了)
                        //3、期数加1，更改开始的状态和时间
                        if ($info['mo_store_uid']) {
                            Db::name('m_goods')
                                ->where('good_p_id', $info['mo_p_id'])
                                ->where('good_user_id', $info['mo_store_uid'])
                                ->inc('good_team_count')
                                ->update(['good_team_status' => 1]);
                        } else {
                            Db::name('product')->where('p_id', $info['mo_p_id'])
                                ->inc('p_m_team_count')
                                ->update(['p_m_team_can_status' => 1]);
                        }
                        //4、开奖(先找出所有的，再排除中过的，最后统一改)
                        $joinUsers = Db::name('m_order')
                            ->where('mo_pay_status', 2)
                            ->where('mo_status', 1)
                            ->where('mo_store_uid', $info['mo_store_uid'])
                            ->where('mo_p_id', $info['mo_p_id'])
                            ->where('mo_team_count', $info['mo_team_count'])
                            ->column('mo_user_id');
                        $todayPriceUser = Db::name('m_order')
                            ->where('mo_get_user_id', '>', 0)
                            ->whereTime('mo_time', 'today')
                            ->group('mo_get_user_id')
                            ->column('mo_get_user_id');
                        $lastUsers = array_diff($joinUsers, $todayPriceUser);
                        if (empty($lastUsers)) {
                            $lastUsers = $joinUsers;
                        }
                        $randUser = rand(0, count($lastUsers) - 1);
                        $get_user_id = $lastUsers[$randUser];
                        Db::name('m_order')
                            ->where('mo_pay_status', 2)
                            ->where('mo_status', 1)
                            ->where('mo_store_uid', $info['mo_store_uid'])
                            ->where('mo_p_id', $info['mo_p_id'])
                            ->where('mo_team_count', $info['mo_team_count'])
                            ->update(['mo_status' => 2, 'mo_get_user_id' => $get_user_id, 'mo_team_money' => $one_good['p_m_team_all_money']]);
                        $getOrderUser = Db::name('m_order')
                            ->where('mo_pay_status', 2)
                            ->where('mo_store_uid', $info['mo_store_uid'])
                            ->where('mo_p_id', $info['mo_p_id'])
                            ->where('mo_team_count', $info['mo_team_count'])
                            ->where('mo_user_id', $get_user_id)
                            ->order('mo_time desc')
                            ->find();
                        //5、入订单表：
                        $j_param1 = [
                            'o_type' => 2,
                            'o_user_id' => $get_user_id,
                            'o_order_num' => $getOrderUser['mo_order_num'],
                            'o_third_order_num' => $getOrderUser['mo_third_order_num'],
                            'o_money' => $getOrderUser['mo_money'],
                            'o_m_money' => $getOrderUser['mo_team_money'],
                            'o_status' => $o_status,
                            'o_pay_type' => $getOrderUser['mo_pay_type'],
                            'o_pay_status' => 2,
                            'o_shop_id' => $getOrderUser['mo_shop_id'],
                            'o_shop_name' => $getOrderUser['mo_shop_name'],
                            'o_cate' => $getOrderUser['mo_cate'],
                            'o_postage' => $getOrderUser['mo_postage'],
                            'o_qrcode' => $getOrderUser['mo_qrcode'],
                            'o_name' => $getOrderUser['mo_name'],
                            'o_phone' => $getOrderUser['mo_phone'],
                            'o_address' => $getOrderUser['mo_address'],
                            'o_m_type' => 3,
                            'o_m_user_id' => $getOrderUser['mo_store_uid'],
                            'o_m_team_uids' => ',' . implode($joinUsers, ',') . ',',
                            'o_add_time' => $getOrderUser['mo_time'],
                        ];
                        $j_get_id1 = Db::name('order')->insertGetId($j_param1);
                        $j_info_param1 = [
                            'oi_order_id' => $j_get_id1,
                            'oi_goods_id' => $getOrderUser['mo_p_id'],
                            'oi_goods_name' => $getOrderUser['mo_goods_name'],
                            'oi_goods_image' => $getOrderUser['mo_goods_image'],
                            'oi_goods_price' => $getOrderUser['mo_goods_price'],
                            'oi_goods_model' => $getOrderUser['mo_goods_model'], //规格名字
                            'oi_num' => 1,
                            'oi_total_price' => $getOrderUser['mo_goods_price'],
                            'oi_total_jifen' => 0
                        ];
                        Db::name('order_info')->insert($j_info_param1);
                        //6、分佣：
                        //-----------------------------分佣 start -----------------------------------------
                        $today = date('Y-m-d H:i:s');
                        $one_fen = [];
                        $one_fen[] = [
                            'record_order_number' => $getOrderUser['mo_order_num'],
                            'record_user_id' => 0,
                            'record_from_type' => 5,
                            'record_payment_type' => $getOrderUser['mo_pay_type'],
                            'record_status' => 2,
//                                'record_get_type' => 1,
                            'record_jifen' => 0,
                            'record_money' => $one_good['p_m_team_system'],
                            'record_add_time' => $today,
                            'record_sure_time' => $today,
                            'record_type' => 2
                        ];
                        $one_fen[] = [
                            'record_order_number' => $getOrderUser['mo_order_num'],
                            'record_user_id' => $get_user_id,
                            'record_from_type' => 8,
                            'record_payment_type' => $getOrderUser['mo_pay_type'],
                            'record_status' => 2,
//                                'record_get_type' => 1,
                            'record_jifen' => $one_good['p_m_team_join_jifen'],
                            'record_money' => $one_good['p_m_team_join_money'],
                            'record_add_time' => $today,
                            'record_sure_time' => $today,
                            'record_type' => 2
                        ];
                        $captain_pay_type = 0;
                        foreach ($haveUsersData as $k => $v) {
                            if ($v['mo_user_id'] == $info['mo_store_uid']) {
                                $captain_pay_type = $v['mo_pay_type'];
                            }
                            $now_v = [
                                'record_order_number' => $getOrderUser['mo_order_num'],
                                'record_user_id' => $v['mo_user_id'],
                                'record_from_type' => 8,
                                'record_payment_type' => $v['mo_pay_type'],
                                'record_status' => 2,
//                                    'record_get_type' => 1,
                                'record_jifen' => 0,
                                'record_money' => $one_good['p_m_team_join_money'],
                                'record_add_time' => $today,
                                'record_sure_time' => $today,
                                'record_type' => 2
                            ];
                            if ($v['mo_user_id'] == $get_user_id) {
                                $now_v['record_from_type'] = 2;
//                                    $now_v['record_get_type'] = 2;
                                $now_v['record_jifen'] = $one_good['p_give'];
                                $now_v['record_money'] = 0;
                                $one_fen[] = $now_v;
                                Db::name('win_info')->insert(['w_info'=>'恭喜拼中'.$oi_goods_name.'商品','w_user_id'=>$get_user_id,'w_type'=>2,'w_add_time'=>date('Y-m-d H:i:s')]);
                                Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，恭喜您，中奖了!并获得推广奖励¥'.$one_good['p_m_team_join_money'].'元，'.$one_good['p_m_team_join_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                try {
                                    $b->jpushUser(1, $get_user_id, '团团赚已开奖，恭喜您中奖~', json([]));
                                } catch (\Exception $e) {
                                }
                            } else {
//                                    $now_v['record_get_type'] = 2;
                                $now_v['record_jifen'] = $one_good['p_m_team_join_jifen'];
                                $one_fen[] = $now_v;

                                Db::name('notice')->insert(['n_to' => 1, 'n_title' => '团团赚开奖', 'n_content' => '购买' . $oi_goods_name . '商品订单参团已开奖，您未中奖，支付金额将原路返回，并获得推广奖励¥'.$now_v['record_money'].'元，'.$now_v['record_jifen'].'积分', 'n_images' => '', 'n_type' => 5, 'n_user_id' => $v['mo_user_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                                try {
                                    $b->jpushUser(1, $v['mo_user_id'], '团团赚已开奖，您未中奖~', json([]));
                                } catch (\Exception $e) {
                                }
                            }
                        }
                        if ($info['mo_store_uid']) {
                            $one_fen[] = [
                                'record_order_number' => $getOrderUser['mo_order_num'],
                                'record_user_id' => $info['mo_store_uid'],
                                'record_from_type' => 7,
                                'record_payment_type' => $captain_pay_type,
                                'record_status' => 2,
//                                    'record_get_type' => 1,
                                'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                'record_money' => $one_good['p_m_team_leader_money'],
                                'record_add_time' => $today,
                                'record_sure_time' => $today,
                                'record_type' => 2
                            ];
                        } else {
                            $one_fen[] = [
                                'record_order_number' => $getOrderUser['mo_order_num'],
                                'record_user_id' => 0,
                                'record_from_type' => 6,
                                'record_payment_type' => 0,
                                'record_status' => 2,
//                                    'record_get_type' => 1,
                                'record_jifen' => $one_good['p_m_team_leader_jifen'],
                                'record_money' => $one_good['p_m_team_leader_money'],
                                'record_add_time' => $today,
                                'record_sure_time' => $today,
                                'record_type' => 2
                            ];
                        }
                        //立即到账
                        if ($getOrderUser['mo_store_uid'] && $getOrderUser['mo_store_uid'] > 0) {
                            $qu = Db::name('u_user')->where('user_id',$getOrderUser['mo_store_uid'])->value('user_area');
                        }else{
                            $qu = Db::name('shop')->where('shop_id',$getOrderUser['mo_shop_id'])->value('shop_qu_id');
                        }
                        $quname = Db::name('area')->where('district_id', $qu)->value('district');
                        $cc = [
                            '3' => '用户购买' . $one_good['p_name'] . '商品返佣',
                            '4' => '用户购买' . $one_good['p_name'] . '商品返佣',
                            '7' => $one_good['p_name'] . '商品团团赚团长奖励',
                            '8' => $one_good['p_name'] . '商品参与团团赚奖励',
                        ];
                        foreach ($one_fen as $fen_k => $fen_v) {
                            if(in_array($fen_v['record_from_type'],[3,4,7,8])) {
                                if ($fen_v['record_money'] > 0) {
                                    Db::name('u_user')->where('user_id', $fen_v['record_user_id'])->setInc('user_m_pool_money', $fen_v['record_money']);
                                }
                                if ($fen_v['record_jifen'] > 0) {
                                    $this->jifenFlow($fen_v['record_jifen'], $qu, $fen_v['record_user_id'], 'poolFenYong');
                                    Db::name('jifen_consume')->insert(['consume_content' => $cc[$fen_v['record_from_type']] . $fen_v['record_jifen'] . "积分({$quname})", 'consume_user_id' => $fen_v['record_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);
                                }
                                //推送待定
//                                    Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                                    $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                            }
                        }
                        Db::name('m_record')->insertAll($one_fen);
                        //-----------------------------分佣 end  ------------------------------------------
                        //6、其他设置
                        Db::name('shop')->where('shop_id', $info['mo_shop_id'])->setInc('shop_balance_yet', $getOrderUser['mo_money']-$getOrderUser['mo_team_money']);
                        Db::name('notice')->insert(['n_to' => 2, 'n_title' => '订单消息', 'n_content' => '您有新的订单！', 'n_images' => '', 'n_type' => 2, 'n_user_id' => $info['mo_shop_id'], 'n_read' => 1, 'n_delete' => 1, 'n_time' => date('Y-m-d H:i:s')]);
                        try {
                            $b->jpushShop(1, $info['mo_shop_id'], '您有新的订单！', ['type2' => 1024, 'msg' => "您有一个新的线上订单"]);
                        } catch (\Exception $e) {
                        }
                    }
                }
                Db::commit ();
            }catch(\Exception $e){
                Db::rollback ();
            }
        }
        exit();
    }
    public function saoma()
    {
        header("Access-Control-Allow-Origin:*");
        $code = input('incode');
        if($code){
            $this->redirect(url('admin/share/register').'?code='.$code);
        }else{
            $this->redirect(url('admin/test/test'));
        }

    }

    /**
     * 举报
     * @return \think\response\Json
     */
    public function jubao(){
        extract (input());
        $user_id = str_replace('jifenshop','',$user_id);
        $other_user_id = str_replace('jifenshop','',$other_user_id);
        $area = Db::name('u_user')->where('user_id',$user_id)->value('user_area');
        $param = [
            'f_type'=>1,
            'f_content'=>$content,
            'f_images'=>$images,
            'f_phone'=>$phone,
            'f_user_id'=>$user_id,
            'f_other_user_id'=>$other_user_id,
            'f_area'=>$area,
            'f_add_time'=>date('Y-m-d H:i:s')
        ];
        $res = Db::name('m_jubao')->insert ($param);
        if($res){
            return json(['status'=>200,'msg'=>'举报成功']);
        }else{
            return json(['status'=>100,'msg'=>'反馈失败，请稍后或刷新重试！']);
        }
    }
    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
        exit('error!');
//        set_time_limit(0);
//        $area = file_get_contents('static/area.json');
//        $area2 = json_decode($area,true);
//        return json($area2);
        set_time_limit(0);
        $pro = Db::table('up_area')
            ->where('pid',1)
//            ->where('district_id',1001)
            ->field('district_id id,district name')
//            ->order('CRI_SORT')
            ->select();
        foreach($pro as $k=>$v){
            $pro[$k]['parentId'] = 0;
            $city = Db::table('up_area')
                ->where('pid',$v['id'])
                ->where('level',2)
                ->field('district_id id,district name,pid parentId')
                ->select();
            foreach ($city as $kk=>$vv){
                $city[$kk]['sub'] = Db::table('up_area')
                    ->where('pid',$vv['id'])
                    ->where('level',3)
                    ->field('district_id id,district name,pid parentId')
                    ->select();
            }
            $pro[$k]['sub'] = $city;
        }
        dump(json_encode($pro)) ;
    }
}